//
//  XHGoodsViewController.m
//  umbs
//
//  Created by 冷山 on 16/6/16.
//  Copyright © 2016年 冷山. All rights reserved.
//

#import "XHGoodsViewController.h"

#import "XHGoodsNameCell.h"
#import "XHGoodsListCell.h"

@interface XHGoodsViewController ()<XHGoodsListCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *ui_tableView;
@property (weak, nonatomic) IBOutlet UILabel *ui_totalMoney;
@property (weak, nonatomic) IBOutlet UILabel *ui_amount;

@property (assign, nonatomic) double ogPrice;
@property (assign, nonatomic) double unitPrice;

@property (strong, nonatomic) UIBarButtonItem * leftItem;

@end

@implementation XHGoodsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHGoodsNameCell" bundle:nil] forCellReuseIdentifier:XHGoodsNameCellIdentifier];
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHGoodsListCell" bundle:nil] forCellReuseIdentifier:XHGoodsListCellIdentifier];
    self.leftItem =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"shouye_icon_baijiantou"] style:UIBarButtonItemStylePlain target:self action:@selector(backActions:)];
    self.navigationItem.leftBarButtonItem=self.leftItem;
    self.leftItem.imageInsets = UIEdgeInsetsMake(1.5, -7, 0, 0);
}

- (void)backActions:(UIBarButtonItem*)item
{
    if ([self.m_myCartArray isKindOfClass:[NSMutableArray class]])
    {
        [_delegate updateGoodsPrice:[NSString stringWithFormat:@"%.2f",[self allPrice]] ogPrice:self.ogPrice];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"BuyReloadData" object:nil];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self updateMyCartView];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger number = 1;
    return number;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rows = 0;
    if ([self.m_myCartArray isKindOfClass:[NSMutableArray class]])
    {
        if(section==0)
        {
            rows=self.m_myCartArray.count+1;
        }
    }
    else
    {
        if (section == 0)
        {
            rows=self.toPayArray.count+1;
        }
    }

    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = nil;
    
    if (indexPath.row==0)
    {
        cell = [self goodsNameCell];
    }
    else
    {
        cell = [self goodsListCell:indexPath];
    }
    return cell;
}

- (XHGoodsNameCell*)goodsNameCell
{
    XHGoodsNameCell * cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHGoodsNameCellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (XHGoodsListCell*)goodsListCell:(NSIndexPath*)indexPath
{
    XHGoodsListCell * cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHGoodsListCellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([self.m_myCartArray isKindOfClass:[NSMutableArray class]])
    {
        cell.delegate = self;
        NSDictionary * dic = self.m_myCartArray[indexPath.row-1];
        cell.dic=dic;
        NSInteger value = [dic[@"productValue"] integerValue];
        if (value>=1000)
        {
            value = value/1000;
            cell.ui_titleLabel.text = [NSString stringWithFormat:@"%@流量%ldG",dic[@"operatorName"],value];
        }
        else if (value<1000)
        {
            cell.ui_titleLabel.text = [NSString stringWithFormat:@"%@流量%ldM",dic[@"operatorName"],value];
        }
//        cell.ui_priceLabel.text = [NSString stringWithFormat:@"￥%.2f",[dic[@"salesPrice"] doubleValue]];self.unitPrice
//        cell.ui_priceLabel.text = [NSString stringWithFormat:@"￥%.2f",self.unitPrice];
        NSString *unitPrice=[NSString stringWithFormat:@"%@",dic[@"salesPrice"]];
        NSNumber *number=[self.m_myCartDictionary objectForKey:dic[@"sequenceNBR"]];
        if ([number integerValue]<=98)
        {
            if (number) {
                cell.ui_countLabel.text=[number stringValue];
                self.unitPrice = [unitPrice doubleValue]*([number integerValue]);
                cell.ui_priceLabel.text = [NSString stringWithFormat:@"￥%.2f",self.unitPrice];
                cell.ui_delButton.hidden=NO;
            }else{
                cell.ui_countLabel.text=@"";
                cell.ui_delButton.hidden=YES;
            }
        }
    }
    else
    {
        cell.ui_addButton.hidden = YES;
        cell.ui_delButton.hidden = YES;
        NSDictionary * dic = self.toPayArray[indexPath.row-1];
        double price = [dic[@"productPrice"] doubleValue];
        NSInteger count= [dic[@"originalCount"] integerValue];
        double allPrice =price*count;
        cell.ui_countLabel.text = [NSString stringWithFormat:@"%@",dic[@"originalCount"]];
        cell.ui_priceLabel.text = [NSString stringWithFormat:@"￥%.2f",allPrice];
        NSString *operator=@"";
        if ([dic[@"operatorCode"]isEqualToString:@"10086"])
        {
            operator = @"中国移动";
        }
        else if ([dic[@"operatorCode"]isEqualToString:@"10010"])
        {
            operator = @"中国联通";
        }
        else if ([dic[@"operatorCode"]isEqualToString:@"10000"])
        {
            operator = @"中国电信";
        }
        NSInteger value = [dic[@"productValue"] integerValue];
        if (value>=1000)
        {
            value = value/1000;
            cell.ui_titleLabel.text = [NSString stringWithFormat:@"%@流量%ldG",operator,value];
        }
        else if (value<1000)
        {
            cell.ui_titleLabel.text = [NSString stringWithFormat:@"%@流量%ldM",operator,value];
        }
    }
    return cell;
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    CGFloat height = 0.1;
    return height;
}

#pragma mark - 商品加减

- (void)cell:(XHGoodsListCell *)cell addButtonAction:(id)sender
{
    NSString *unitPrice=[NSString stringWithFormat:@"%@",cell.dic[@"salesPrice"]];
    NSString *foodKey=[NSString stringWithFormat:@"%@",cell.dic[@"sequenceNBR"]];
    NSNumber *number=[self.m_myCartDictionary objectForKey:foodKey];
    if([number integerValue]<=98)
    {
        if (number) {
            [self.m_myCartDictionary setObject:@([number integerValue]+1) forKey:foodKey];
            self.unitPrice = [unitPrice doubleValue]*([number integerValue]+1);
        }else
        {
            [self.m_myCartDictionary setObject:@1 forKey:foodKey];
            [self.m_myCartArray addObject:cell.dic];
        }
        [self.ui_tableView reloadData];
        [self updateMyCartView];
    }
}

- (void)cell:(XHGoodsListCell *)cell delButtonAction:(id)sender
{
    NSString *foodKey=[NSString stringWithFormat:@"%@",cell.dic[@"sequenceNBR"]];
    NSNumber *number=[self.m_myCartDictionary objectForKey:foodKey];
    NSInteger count=[number integerValue]-1;
    if (count<=0) {
        [self.m_myCartDictionary removeObjectForKey:foodKey];
        [self.m_myCartArray removeObject:cell.dic];
    }else
    {
        [self.m_myCartDictionary setObject:@(count) forKey:foodKey];
    }
    [self.ui_tableView reloadData];
    [self updateMyCartView];
}


- (void)updateMyCartView
{
    [self.ui_tableView reloadData];
    if ([self.m_myCartArray isKindOfClass:[NSMutableArray class]])
    {
        if ([self allCount]==0)
        {
            self.ui_amount.text=[NSString stringWithFormat:@"(总计数量 0)"];
        }
        self.ui_amount.text=[NSString stringWithFormat:@"（总计数量 %lu）",(unsigned long)[self allCount]];
        self.ui_totalMoney.text=[NSString stringWithFormat:@"￥%.2f",[self allPrice]];
    }
    else
    {
        int allCount=0;
        for (NSDictionary * dic in self.toPayArray)
        {
           int count = [dic[@"originalCount"] intValue];
            allCount+=count;
        }
        self.ui_totalMoney.text = [NSString stringWithFormat:@"￥%@",self.toPayDic[@"amount"]];
        self.ui_amount.text = [NSString stringWithFormat:@"（总计数量 %d）",allCount];
    }
}

- (NSUInteger)allCount{
    double allPrice=0;
    NSUInteger allCount=0;
    for (NSDictionary *dic in self.m_myCartArray) {
        double price=[dic[@"salesPrice"] doubleValue];
        NSString *foodKey=dic[@"sequenceNBR"];
        int count=[self.m_myCartDictionary[foodKey] intValue];
        allPrice+=(count*price);
        allCount+=count;
    }
    return allCount;
}

- (double)allPrice{
    double allPrice=0;
    double allCount=0;
    double ogPrice=0;
    self.ogPrice = ogPrice;
    for (NSDictionary *dic in self.m_myCartArray) {
        double price=[dic[@"salesPrice"] doubleValue];
        double prices=[dic[@"marketPrice"] doubleValue];
        NSString *foodKey=dic[@"sequenceNBR"];
        int count=[self.m_myCartDictionary[foodKey] intValue];
        allPrice+=(count*price);
        allCount+=count;
        ogPrice+=(count*prices);
        self.ogPrice = ogPrice;
    }
    return allPrice;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
